package controller;

import domain.User;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import service.UserService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@Controller
public class UserController {

    @Autowired
    private UserService userService;

/*    @RequestMapping("login")
    public ModelAndView findByName(String username, String password) {

        ModelAndView mv;
        mv = new ModelAndView();
        User user = userService.findByName(username, password);
        if (user == null) {
            mv.addObject("message","用户名或密码错误！");
            mv.setViewName("login");
        } else {
            mv.addObject("user", user);
            mv.setViewName("success");
        }
        return mv;
    }*/

    @RequestMapping(value = "/login")
    public String login(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws ServletException, IOException {

        Map<String, String[]> map = request.getParameterMap();
        //创建User对象
        User loginUser = new User();
        //使用BeanUtil封装
        try {
            BeanUtils.populate(loginUser,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }


        User user = userService.login(loginUser);
//        System.out.println(user);


        if(user!=null){
            session.setAttribute("user",user);
            return "redirect:/success.jsp";
        }
        request.setAttribute("msg", "用户名或密码错误！");
        request.getRequestDispatcher("/login.jsp").forward(request, response);
        return "redirect:/login.jsp";
    }
}
